import {Button, message, Select} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryRule,exportDayStock,exportTestStock} from './service';
import {saveFileAs} from '@/utils/utils';
import CreateForm from "@/pages/OrderManagement/StoreOrder/components/CreateForm";
import styles from "@/global.less";
import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import Access from '@/components/Access/Access';
import moment from "moment";

const TableList = (props) => {
  const actionRef = useRef();
  const [storeArray, setStoreArray] = useState([]);
  const [count, setCount] = useState();

  const [settleRecords, setSettleRecords] = useState(false);
  const [outModal, handleOutModal] = useState(false);

  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getStore();
  }, []);

  const columns = [
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options){
                option.options.map((data=>{
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }))
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id} >
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeName',
      hideInSearch:true,
    },
    {
      title: '商品',
      dataIndex: 'goodsItemName',
    },
    {
      title: '条码',
      dataIndex: 'barCode',
    },
    {
      title: '归档日期',
      dataIndex: 'dataTime',
      valueType: 'date',
      initialValue: moment(new Date()).subtract(1,'d').format('YYYY-MM-DD'),
    },
    {
      title: '归档库存结余',
      dataIndex: 'stock',
      hideInSearch: true,
    },
    {
      title: '归档成本价',
      dataIndex: 'cost',
      hideInSearch: true,
    },
    {
      title: '归档市场价',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '归档会员价',
      dataIndex: 'memberPrice',
      hideInSearch: true,
    },
    {
      title: '归档积分价',
      dataIndex: 'integralPrice',
      hideInSearch: true,
    },
    {
      title: '归档价格类型',
      dataIndex: 'priceType',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '授权价',
          status: 'Processing',
        },
        2: {
          text: '店铺价',
          status: 'Success',
        },
      },
    },
    {
      title: '归档结算类型',
      dataIndex: 'cycleType',
      hideInSearch: true,
      valueEnum: {
        3: {
          text: '周结',
          status: 'Processing',
        },
        4: {
          text: '月结',
          status: 'Success',
        },
        5: {
          text: '暂无',
          status: 'Success',
        },
      },
    },
  ];
  const outColumns = [
    {
      title: '归档日期',
      dataIndex: 'dataTime',
      valueType: 'date',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '归档日期为必选项',
          },
        ],
      },
    },
    {
      title: '归档店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择归档店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options){
                option.options.map((data=>{
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }))
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id} >
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="库存列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1200}}
        bordered
        toolBarRender={() => [
          <Access accessKey={"@exportDayStock"}>
            <Button loading={settleRecords} type="primary" onClick={() => {
              handleOutModal(true);
              setSettleRecords(true);
            }}>
              导出库存记录
            </Button>
          </Access>
          ,
        ]}
        request={(params, sorter, filter) => queryRule({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />
      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => {
          handleOutModal(false);
          setSettleRecords(false);
        }}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutModal(false);
            exportDayStock(value).then(res=>{
              if (res){
                saveFileAs(res, '归档库存记录');
              }
              setSettleRecords(false);
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
